#include <assert.h>
#include <stdio.h>
#include "Grenade.h"
#include "include.h"

Grenade::Grenade(TextureManager * textureManager, Object * owner, float strength, float fuse, float maxThrowStrength, float mass)
:Weapon(owner)
{
	this->textureManager = textureManager;
	if(textureManager)
	{
		if(!textureManager->LoadTexture(GRENADE_TEXTURE))
				printf("Loading %s failed!", GRENADE_TEXTURE);
		if(!textureManager->LoadTexture(EXPLOSION_TEXTURE))
				printf("Loading %s failed!", EXPLOSION_TEXTURE);
	}
	count = 0;
	this->owner = owner;
	this->strength = strength;
	this->fuseLength = fuse;
	this->maxThrowStrength = maxThrowStrength * 10;
	this->mass = mass;
	
	grenade = NULL;
}

Grenade::~Grenade()
{
	//if(grenade != NULL)
	//	free(grenade);
	grenade = NULL;	
}
	
void Grenade::UseWeapon(Object * target)
{
	printf("using weapon\n");
	if(grenade)
		return;
	//printf("Grenade UseWeapon\n");
	Vector2D towardTarget = owner->position - target->position;
	towardTarget = !towardTarget;
	towardTarget *= -maxThrowStrength;
	Material * material = new Material("grenade",0,0,true,0.1,-1);
	Vector2D * vertices = (Vector2D *)malloc(sizeof(Vector2D)*4);
	assert(vertices != NULL);
	vertices[0] = Vector2D(-2,2);
	vertices[1] = Vector2D(2,2);
	vertices[2] = Vector2D(2,-2);
	vertices[3] = Vector2D(-2,-2);
	
	Vector2D throwPos = owner->position;
	if(owner->numVertices > 0)
		 throwPos = throwPos + owner->vertices[0] * 1.5;
	grenade = new GrenadeObject(textureManager,throwPos, Vector2D(0.0, 0.0), towardTarget, 
						 		0.0, 0.0, 0.0, mass, fuseLength, strength, false);
	grenade->AddForce(towardTarget);
	grenade->AddForce(Vector2D(-2,2), towardTarget * 0.5);
	owner->objectToCreate = grenade;
	count ++;				 		
}

bool Grenade::CanUseWeapon(double elapsedTime)
{
	if(IsUsingWeapon() || IsWaitingForWeapon())
	{
		return false;
	}
		
	float maxDistance = maxThrowStrength * elapsedTime;
	
	maxDistance  = maxDistance * maxDistance / (-1 * GRAVITATIONAL_FORCE * mass); 
	maxDistance *= 1.5;
	float distance = owner->position.dist(target->position);
	return distance <= maxDistance;
}
bool Grenade::IsUsingWeapon()

{
	return grenade != NULL;
}
bool Grenade::IsWaitingForWeapon()
{
	return grenade != NULL;
}
void Grenade::WeaponThinkEntryPoint(double elapsedTime, Object * target, bool isCapable)
{
	if(grenade != NULL && grenade->IsDone())
	{
		grenade = NULL;
	}
}